package core;

import java.awt.geom.Point2D;

import gui.PlayersMap;

//physics class for gaming
public class Physics extends Thread {
	private boolean started = false;
	private PlayersMap map;
	private static double energyX, energyY;
	private double m, dx, dy, v, dist, energy;
//	private double vx, vy, a; //"a" is for the friction only 
	private double cosFi, sinFi, weight;
	private final double g = 9.80665;
	private int timeQuantum = 20;
	private double time = timeQuantum / 1000d;
	
	//it starts the time
	public void startTime(){
		started = true;
		start();
	}
	
	//it stops the time
	public void stopTime(){
		started = false;
	}
	
	//constructor. it sets the map controlled by this physics
	public Physics(PlayersMap map){
		this.map = map;
		m = map.getBallMass();
		weight = m * g;
	}
	
	//the body was affected with momentum 
	public void energyPassing(double eX, double eY){
		//the energy is the only information about the direction
		energyX += eX * map.getManoeuvrability();
		energyY += eY * map.getManoeuvrability();
		energy = Math.sqrt(energyX*energyX + energyY*energyY);
		v = Math.sqrt( (2d*energy) / m );
	}
	
	/**
	 * @param vx, vy
	 * 	sets the ball velocity
	 */
	public static void setVelocity(double vx, double vy){
		energyX = vx;
		energyY = vy;
	}
	
	/**
	 * @return
	 * 	the ball velocity
	 */
	public static Point2D getVelocity(){
		return new Point2D.Double(energyX, energyY);
	}
	
	//override for thread running
	public void run(){
		try {
			sleep(500);
		} catch (InterruptedException e1) {}
		
		while(started){
			try {
				double ff = weight * map.getFrictionalCoefficient();

				if(energy != 0){
					cosFi = energyX / energy;
					sinFi = energyY / energy;
				}else{
					cosFi = 0;
					sinFi = 0;
				}
				
				double var = (ff / m) * time;
				dist = time*(v - var / 2);
				v = v - var;
				
				if( (dist > 0) && (v > 0) ){
					energy = m*v*v/2d;
					
					dx = dist * cosFi;
//					vx = v * cosFi;
					energyX = energy * cosFi;
					
					dy = dist * sinFi;
//					vy = v * sinFi;
					energyY = energy * sinFi;
				}else{
					dist = 0;
					v = 0;
					energy = 0;
					energyX = 0;
					energyY = 0;
					dx = 0;
					dy = 0;
				}

				if(!map.moveBall(dx, dy, energyX, energyY)){			
					sleep(timeQuantum);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}